﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using Dapper;
using DapperExtensions;
using ExaminationSys.DataAccess.Entity;
using SQLinq;
using SQLinq.Dapper;

namespace ExaminationSys.DataAccess.Repository
{
    public class StudentTestHistoryRepository : Repository<StudentTestHistory>
    {
        public StudentTestHistoryRepository(SqlConnection context)
            : base(context)
        {
            db = context;
        }
        private SqlConnection db;
        public override StudentTestHistory GetById(dynamic id)
        {
            return base.ObjectSet.Get<StudentTestHistory>(db, id, null, null);
        }
    }

    public class StudentTestHistoryService
    {
        private static readonly StudentTestQuestionService ProxyQuestion = ObjectFactory<StudentTestQuestionService>.Create();
        private static readonly DBAnswerService DBAnswerProxy = ObjectFactory<DBAnswerService>.Create();
        private static readonly PaperInfoService PaperInfoProxy = ObjectFactory<PaperInfoService>.Create();
        private static readonly PaperDetailAutoService PaperDetailAutoProxy = ObjectFactory<PaperDetailAutoService>.Create();
        private static readonly DBQuestionService DBQuestionProxy = ObjectFactory<DBQuestionService>.Create();
        
        private StudentTestHistoryService()
        {
        }
        public StudentTestHistory Get(Guid id)
        {
            using (var db = DataContent.DBServer())
            {
                IUnitOfWork work = new UnitOfWork(db);
                var result = work.StudentTestHistory.GetById(id);
                return result;

            }
        }
        public List<StudentTestHistory> GetStudentPaper(string studentid)
        {
            using (var db = DataContent.DBServer())
            {
                var pg = new PredicateGroup {Operator = GroupOperator.And, Predicates = new List<IPredicate>()};
                pg.Predicates.Add(Predicates.Field<StudentTestHistory>(f => f.StudentID, Operator.Eq, studentid));
                IUnitOfWork work = new UnitOfWork(db);
                var result = work.StudentTestHistory.GetList(pg).ToList();
                return result;
            }
        }
        public StudentTestHistory GetStudentPaper(Guid studentId, Guid paperId)
        {
            using (var db = DataContent.DBServer())
            {
                var pg = new PredicateGroup {Operator = GroupOperator.And, Predicates = new List<IPredicate>()};
                pg.Predicates.Add(Predicates.Field<StudentTestHistory>(f => f.StudentID, Operator.Eq, studentId));
                pg.Predicates.Add(Predicates.Field<StudentTestHistory>(f => f.PaperInfoID, Operator.Eq, paperId));
                pg.Predicates.Add(Predicates.Field<StudentTestHistory>(f => f.Status, Operator.Eq, -1, true));
                IUnitOfWork work = new UnitOfWork(db);
                var result = work.StudentTestHistory.GetList(pg).FirstOrDefault();
                return result;
            }
        }

        public bool CheckStudentPaper(string studentid, string paperinfoid)
        {
            using (var db = DataContent.DBServer())
            {
                var pg = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() };
                pg.Predicates.Add(Predicates.Field<StudentTestHistory>(f => f.StudentID, Operator.Eq, studentid));
                pg.Predicates.Add(Predicates.Field<StudentTestHistory>(f => f.PaperInfoID, Operator.Eq, paperinfoid));
                IUnitOfWork work = new UnitOfWork(db);
                var result = work.StudentTestHistory.GetList(pg).FirstOrDefault();
                return result != null;
            }
        }

        public StudentTestHistory CheckStudentPaper2(string studentid, string paperinfoid)
        {
            using (var db = DataContent.DBServer())
            {

                var pg = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() };
                pg.Predicates.Add(Predicates.Field<StudentTestHistory>(f => f.StudentID, Operator.Eq, studentid));
                pg.Predicates.Add(Predicates.Field<StudentTestHistory>(f => f.PaperInfoID, Operator.Eq, paperinfoid));
                IUnitOfWork work = new UnitOfWork(db);
                var result = work.StudentTestHistory.GetList(pg);
                return result == null ? null : result.ToList().Count > 0 ? result.ToList()[0] : null;
            }
        }
        public StudentTestHistory CheckStudentPaper3(string studentid, string paperinfoid)
        {
            using (var db = DataContent.DBServer())
            {
                var pg = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() };
                pg.Predicates.Add(Predicates.Field<StudentTestHistory>(f => f.StudentID, Operator.Eq, studentid));
                pg.Predicates.Add(Predicates.Field<StudentTestHistory>(f => f.PaperInfoID, Operator.Eq, paperinfoid));
                IUnitOfWork work = new UnitOfWork(db);
                var result = work.StudentTestHistory.GetList(pg);
                if (result != null)
                {
                    List<StudentTestHistory> list = result.ToList();
                    if (list.Count > 0)
                    {
                        foreach (StudentTestHistory sth in list)
                        {
                            if (sth.Status == -1)
                                return sth;
                        }
                        return list[0];
                    }                        
                }
                return null;
            }
        }

        public StudentTestHistory GetStudentHistoryByStudentIdAndPaperId(string studentid, string paperinfoid)
        {
            using (var db = DataContent.DBServer())
            {
                var sql =
                    string.Format(
                        @"SELECT *
                      FROM StudentTestHistory sth
                    WHERE sth.StudentID='{0}'
                    AND sth.PaperInfoID='{1}'
                     ORDER BY sth.TestStartTime desc",
                        studentid, paperinfoid);
                var result =
                    db.Query<StudentTestHistory>(sql).
                        FirstOrDefault();
                return result;
            }
        }

        public List<StudentTestHistory> GetAll()
        {
            using (var db = DataContent.DBServer())
            {
                IUnitOfWork work = new UnitOfWork(db);
                var result = work.StudentTestHistory.GetList();
                return result.ToList();
            }
        }

        public bool Delete(List<string> ids)
        {
            if (ids == null || ids.Count == 0) return false;
            bool flag = false;
            using (var db = DataContent.DBServer())
            {
                int retCode = 0;
                foreach (var id in ids)
                {
                    retCode = db.Execute(@"delete from StudentTestHistory where ID=@TmpId",
                                         new[] { new { TmpId = id } });
                    if (retCode <= 0)
                    {
                        break;
                    }
                }
                flag = true;
            }
            return flag;
        }

        public bool Lock(List<string> ids, int _lock)
        {
            if (ids == null || ids.Count == 0) return false;
            bool flag = false;
            using (var db = DataContent.DBServer())
            {
                int retCode = 0;
                foreach (var id in ids)
                {
                    retCode = db.Execute(@"update StudentTestHistory set Lock=@lk where ID=@TmpId",
                                         new[] { new { lk = _lock, TmpId = id } });
                    if (retCode <= 0)
                    {
                        break;
                    }
                }
                flag = true;
            }
            return flag;
        }

        public bool Update(StudentTestHistory entity)
        {
            using (var db = DataContent.DBServer())
            {
                IUnitOfWork work = new UnitOfWork(db);
                return work.StudentTestHistory.Update(entity);
            }
        }
        public dynamic Insert(StudentTestHistory entity)
        {
            using (var db = DataContent.DBServer())
            {
                IUnitOfWork work = new UnitOfWork(db);
                return work.StudentTestHistory.Insert(entity, null);
            }
        }

        public List<StudentTestHistory> GetListByPage(string sqlwhere, string orderbyFiled, int pagesize, int pageindex, out int totalPage, out int totalRecord)
        {
            if (string.IsNullOrWhiteSpace(orderbyFiled))
                throw new ArgumentNullException("orderbyFiled");

            if (string.IsNullOrWhiteSpace(sqlwhere))
                sqlwhere = " 1=1";
            using (var db = DataContent.DBServer())
            {
                var obj = new
                {
                    TableName = "StudentTestHistory",
                    Fields = "*",
                    OrderField = orderbyFiled,
                    sqlWhere = sqlwhere,
                    pageSize = pagesize,
                    pageIndex = pageindex,
                };

                var dynamicParam = new DynamicParameters(obj);
                dynamicParam.Add("TotalPage", null, DbType.Int32, ParameterDirection.Output, 32);
                dynamicParam.Add("TotalRecord", 0, DbType.Int32, ParameterDirection.Output, 32);

                var items = db.Query<StudentTestHistory>("PagingRecord", dynamicParam, null, true, null, CommandType.StoredProcedure);
                totalPage = dynamicParam.Get<int>("TotalPage");
                totalRecord = dynamicParam.Get<int>("TotalRecord");
                return items.ToList();
            }
        }
        public List<StudentTestHistorySearchEntity> GetHistoryListByPage(string sqlwhere, string orderbyFiled, int pagesize, int pageindex, out int totalPage, out int totalRecord)
        {
            if (string.IsNullOrWhiteSpace(orderbyFiled))
                throw new ArgumentNullException("orderbyFiled");

            if (string.IsNullOrWhiteSpace(sqlwhere))
                sqlwhere = " 1=1";
            using (var db = DataContent.DBServer())
            {
             
                var obj = new
                {
                    TableName = "StudentTestHistory",
                    Fields = "*",
                    OrderField = orderbyFiled,
                    sqlWhere = sqlwhere,
                    pageSize = pagesize,
                    pageIndex = pageindex,
                };

                var dynamicParam = new DynamicParameters(obj);
                dynamicParam.Add("TotalPage", null, DbType.Int32, ParameterDirection.Output, 32);
                dynamicParam.Add("TotalRecord", 0, DbType.Int32, ParameterDirection.Output, 32);

                var items = db.Query<StudentTestHistorySearchEntity>("PagingRecord", dynamicParam, null, true, null, CommandType.StoredProcedure);
                totalPage = dynamicParam.Get<int>("TotalPage");
                totalRecord = dynamicParam.Get<int>("TotalRecord");
                return items.ToList();
            }
        }
        public string GetStudentTestHistoryID(string studentid,string paperid)
        {
            using (var db = DataContent.DBServer())
            {
                StringBuilder sb = new StringBuilder("");
                string strWhere=string.Format(" StudentID='{0}' and PaperInfoID='{1}'", studentid, paperid);
                sb.Append("select * from StudentTestHistory where ");
                sb.Append(strWhere);
                sb.Append(" order by TotalPoint DESC");

                var items = db.Query<StudentTestHistory>(sb.ToString());
                List <StudentTestHistory> list= items.ToList();
                string temp=string.Empty;
                if (list != null && list.Count > 0)
                    temp = list[0].ID.ToString();

                return temp;
            }
        }

        /// <summary>
        /// 获取学生考试的评语
        /// </summary>
        /// <param name="studentid"></param>
        /// <param name="paperid"></param>
        /// <returns></returns>
        public PaperFeedback GetStudentTestComment(Guid studentid,Guid paperid)
        {
            using (var db = DataContent.DBServer())
            {
                StringBuilder sb = new StringBuilder("");

                sb.AppendFormat(" select  * from  PaperFeedback fb");
                sb.AppendFormat(" inner join PaperFeedBackComment fbc ");
                sb.AppendFormat(" on fb.PaperFeedBackCommentID = fbc.ID");
                sb.AppendFormat(" inner join PaperInfo paper");
                sb.AppendFormat(" on fbc.ID = paper.PaperFeedBackCommentID");
                sb.AppendFormat(" inner join  StudentTestHistory test");
                sb.AppendFormat(" on test.PaperInfoID = paper.ID");
                sb.AppendFormat(" where ");
                sb.AppendFormat(" fb.StartValue<= test.TotalPoint and test.TotalPoint<= fb.EndValue  ");
                sb.AppendFormat(" and paper.ID ='{0}'", paperid);
                sb.AppendFormat(" and test.StudentID ='{0}'", studentid);

                try
                {
                    var items = db.Query<PaperFeedback>(sb.ToString());
                    List<PaperFeedback> list = items.ToList();

                    //评语取一个
                    return list.First();
                }
                catch (Exception)
                {
                    return null;
                }
             

            }


        }


        public List<ChartData> GetTestHistoryChartData(Guid studentid)
        {

             using (var db = DataContent.DBServer())
            {
                StringBuilder sb = new StringBuilder("");

                sb.AppendFormat(" select top 7  convert(char(8),sth.TestStartTime,2) as Name,convert(numeric(8,2), (sth.TotalPoint/tq.Total)*100) as DataValue   from StudentTestHistory sth ");
                sb.AppendFormat(" inner join                                                                                                      ");
                sb.AppendFormat(" (select  sum(Point) as Total,TestHistoryID from StudentTestQuestion   group by TestHistoryID) tq                ");
                sb.AppendFormat(" on tq.TestHistoryID = sth.ID                                                                                    ");
                sb.AppendFormat(" inner join                                                                                                      ");
                sb.AppendFormat(" PaperInfo  pa                                                                                                   ");
                sb.AppendFormat(" on pa.ID = sth.PaperInfoID                                                                                      ");
                sb.AppendFormat(" where sth.StudentID='{0}'", studentid);

                try
                {
                    var items = db.Query<ChartData>(sb.ToString());
                    List<ChartData> list = items.ToList();
                    return list;
                }
                catch (Exception)
                {
                    return null;
                }
             }
        }
               
 
        public List<PaperQuestion> GetListPageByPaperID(string strwhere)
        {
            using (var db = DataContent.DBServer())
            {
                StringBuilder sb = new StringBuilder("select * from View_PaperQuestion where ");
                sb.Append(strwhere);
                sb.Append(" order by AddTime DESC");

                var items = db.Query<PaperQuestion>(sb.ToString());
                return items.ToList();
            }
        }


        private string GetRightAnswer(List<DBAnswer> list)
        {
            string temp = string.Empty;
            if (list != null && list.Count > 0)
            {
                foreach (DBAnswer aBAnswer in list)
                {
                    if (aBAnswer.IsRight)
                        temp += aBAnswer.Prefix.Trim();
                }
            }
            return temp;
        }

        public List<StudentPaperQuestionAnswer> StudentPaper(string paperid, string studentid, ref Guid testHistoryId)
        {
            if (paperid == null || studentid == null)
                return null;

            PaperInfo pi = PaperInfoProxy.Get(new Guid(paperid));
            if (pi == null)
                return null;

            StudentTestHistory sth = CheckStudentPaper3(studentid, paperid);

            Guid testhistoryid=Guid.NewGuid();
            if (sth == null || sth.Status == 1)
            {
                #region 生成学生试卷
                if (pi.Type == 1)
                    StudentPaperQuestionBuildFix(paperid, studentid, pi, ref testhistoryid);
                else if (pi.Type == 2)
                    StudentPaperQuestionBuildAuto(paperid, studentid, pi, ref testhistoryid);
                else
                    return null;
                testHistoryId = testhistoryid;
                #endregion
            }
            else
            {   // 试卷题目检查
                StudentPaperQuestionCheck(sth, pi);
                testHistoryId = sth.ID;
            }

            List<StudentPaperQuestion> spqList = ProxyQuestion.GetListQuestionByPSID(sth, studentid, paperid);
            List<StudentPaperQuestionAnswer> spqalist = new List<StudentPaperQuestionAnswer>();

            if (spqList != null && spqList.Count > 0)
            {
                #region 考试题目列表
                int rowindex = 1;
                foreach (StudentPaperQuestion spd in spqList)
                {
                    List<DBAnswer> dalist = DBAnswerProxy.GetQuestionAnswer(spd.ID.ToString());
                    StudentPaperQuestionAnswer spqa = new StudentPaperQuestionAnswer();
                    spqa.studentPaperQuestion = spd;
                    spqa.listDBAnswer = dalist;
                    spqa.questionindex = rowindex;
                    spqalist.Add(spqa);
                    rowindex++;
                    dalist = new List<DBAnswer>();
                }
                #endregion
            }

            return spqalist;
        }
        public void StudentPaperQuestionCheck(StudentTestHistory sth, PaperInfo pi)
        {
            if (pi.Type == 1)
                StudentPaperQuestionBuildFixCheck(sth, pi);
            else if (pi.Type == 2)
                StudentPaperQuestionBuildAutoCheck(sth, pi);
        }

        public Guid StudentPaperAdd(string paperid, string studentid, PaperInfo pi)
        {
            StudentTestHistory studentTestHistory = new StudentTestHistory();
            studentTestHistory.PaperInfoID = new Guid(paperid);
            studentTestHistory.Status = -1;
            studentTestHistory.StudentID = new Guid(studentid);
            studentTestHistory.TestStartTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            studentTestHistory.TotalPoint = 0;
            studentTestHistory.Title = "";
            studentTestHistory.TestEndTime = studentTestHistory.TestStartTime.AddMinutes(pi.Timeout);
            studentTestHistory.TestPauseTime = studentTestHistory.TestStartTime.AddMinutes(5);
            studentTestHistory.SectionID = pi.SectionID;

            var retCode = Insert(studentTestHistory);
            return retCode;
        }

        public bool StudentPaperQuestionBuildFix(string paperid, string studentid, PaperInfo pi,ref Guid testHistoryId)
        {
            #region 新添加
            bool sucess = false;
            var retCode = StudentPaperAdd(paperid, studentid, pi);
            testHistoryId = retCode;
            if (retCode != null)
            {
                string strWhere = string.Format(" Paperid='{0}'", paperid);
                List<PaperQuestion> list = GetListPageByPaperID(strWhere);

                sucess = StudentPaperQuestionAdd(list, retCode);
            }
            if (!sucess)
            {
                List<string> l = new List<string>();
                l.Add(retCode.ToString());
                Delete(l);
            }
            #endregion

            return sucess;
        }
        public bool StudentPaperQuestionBuildAuto(string paperid, string studentid, PaperInfo pi, ref Guid testHistoryId)
        {
            if (pi != null && pi.ID != null)
            {
                List<PaperDetailAuto> pdalist = PaperDetailAutoProxy.GetPaperDetailAuto(paperid);
                if (pdalist != null && pdalist.Count > 0)
                {
                    bool sucess = true;
                    var retCode = StudentPaperAdd(paperid, studentid, pi);
                    testHistoryId = retCode;
                    sucess = retCode != null;
                    if (sucess)
                    {
                        List<DBQuestion> dBQuestion = new List<DBQuestion>();
                        try
                        {
                            #region 选择题目
                            foreach (PaperDetailAuto pda in pdalist)
                            {
                                if (pda != null && pda.ExerciseCount > 0)
                                {
                                    List<DBQuestion> dBQuestionList = DBQuestionProxy.GetAll(pda);
                                    if (dBQuestionList != null && dBQuestionList.Count >= pda.ExerciseCount)
                                        GetQuestionList(ref dBQuestion, pda.ExerciseCount, dBQuestionList);
                                    else
                                    {
                                        sucess = false;
                                        break;
                                    }
                                }
                            }
                            #endregion
                        }
                        catch { sucess = false; }
                        if (sucess && dBQuestion != null && dBQuestion.Count > 0)
                        {
                            #region 添加学生题目
                            List<string> deleteids = new List<string>();

                            if (dBQuestion != null && dBQuestion.Count > 0)
                            {
                                string rightanswer = string.Empty;
                                StudentTestQuestion tempstq = new StudentTestQuestion();
                                tempstq.Status = 1;
                                tempstq.StudentAnswer = "";
                                tempstq.StudentPoint = 0;
                                tempstq.TestHistoryID = retCode;

                                try
                                {
                                    var tempRetCode = new Guid();
                                    foreach (DBQuestion dbq in dBQuestion)
                                    {
                                        List<DBAnswer> dalist = DBAnswerProxy.GetQuestionAnswer(dbq.ID.ToString());
                                        if (dalist != null && dalist.Count > 0)
                                        {
                                            rightanswer = GetRightAnswer(dalist);
                                            StudentTestQuestion stq = tempstq;
                                            stq.Point = dbq.Point;
                                            stq.RightAnswer = rightanswer;
                                            stq.QuestionID = dbq.ID;
                                            stq.AnswerTime = System.DateTime.Now;
                                            if (!ProxyQuestion.CheckStudentPaper(dbq.ID.ToString(), retCode.ToString()))
                                            {
                                                tempRetCode = ProxyQuestion.Insert(stq);
                                                if (tempRetCode != null)
                                                    deleteids.Add(tempRetCode.ToString());
                                                else
                                                {
                                                    sucess = false;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                                catch { sucess = false; }
                            }
                            if (!sucess && deleteids != null && deleteids.Count > 0)
                                ProxyQuestion.Delete(deleteids);

                            #endregion
                        }
                    }
                    if (!sucess && retCode != null)
                    {
                        List<string> l = new List<string>();
                        l.Add(retCode.ToString());
                        Delete(l);
                    }
                    return sucess;
                }
            }
            return false;
        }
        public void GetQuestionList(ref List<DBQuestion> dBQuestion,
            int exerciseCount, List<DBQuestion> dBQuestionList)
        {
            dBQuestion = dBQuestion == null ? new List<DBQuestion>() : dBQuestion;

            if (exerciseCount == dBQuestionList.Count)
                foreach (DBQuestion dbq in dBQuestionList)
                    dBQuestion.Add(dbq);
            else
            {
                List<int> se = GetRandList(0, dBQuestionList.Count - 1, exerciseCount);
                foreach (int rowindex in se)
                    dBQuestion.Add(dBQuestionList[rowindex]);
            }
        }
        public void GetQuestionList(ref List<DBQuestion> dBQuestion, int exerciseCount, 
            List<DBQuestion> dBQuestionList, List<DBQuestion> exitdBQuestionList, int existscount)
        {
            bool addflag = true;
            if (exerciseCount == dBQuestionList.Count)
            {
                foreach (DBQuestion dbq in dBQuestionList)
                {
                    foreach (DBQuestion db in exitdBQuestionList)
                    {
                        if (dbq.ID.Equals(db.ID))
                        {
                            addflag = false; break;
                        }
                    }
                    if (addflag && existscount < exerciseCount)
                    {
                        dBQuestion.Add(dbq);
                        existscount++;
                    }
                    addflag = true;
                }
            }
            else
            {
                List<int> se = GetRandList(0, dBQuestionList.Count - 1, exerciseCount);
                foreach (int rowindex in se)
                {
                    foreach (DBQuestion db in exitdBQuestionList)
                    {
                        if (dBQuestionList[rowindex].ID.Equals(db.ID))
                        {
                            addflag = false; break;
                        }
                    }
                    if (addflag && existscount < exerciseCount)
                    {
                        dBQuestion.Add(dBQuestionList[rowindex]);
                        existscount++;
                    }
                    addflag = true;
                }

            }
        }

        #region 获取指定范围的部分随机数
        public List<int> GetRandList(int minValue, int maxValue, int count)
        {
            maxValue = maxValue - minValue + 1;
            List<int> arrInt = new List<int>();

            for (int i = 0; i < maxValue; i++)
            {
                arrInt.Add(i + minValue);
            }

            List<int> arrResult = new List<int>();
            int n = maxValue;
            Random rand = new Random();

            for (int i = 0; i < count; i++)
            {
                int index = rand.Next(0, n);
                arrResult.Add(arrInt[index]);
                arrInt[index] = arrInt[--n];
            }
            return arrResult;
        }
        #endregion

        public bool StudentPaperQuestionBuildFixCheck(StudentTestHistory sth, PaperInfo pi)
        {
            bool success = false;

            List<PaperQuestion> list = ProxyQuestion.GetPaperQuestionNotInStudentPaperQuestionList(sth);
            if (list != null && list.Count > 0)
                success = StudentPaperQuestionAdd(list, sth.ID);

            List<StudentTestQuestion> list2 = ProxyQuestion.GetStudentPaperQuestionNotInPaperQustionList(sth);
            if (list2 != null && list2.Count > 0)
            {
                List<string> listids = new List<string>();
                foreach (StudentTestQuestion stq in list2)
                    listids.Add(stq.QuestionID.ToString());
                success = ProxyQuestion.Delete(listids);
            }

            return success;
        }
        public bool StudentPaperQuestionBuildAutoCheck(StudentTestHistory sth, PaperInfo pi)
        {
            bool sucess = true;
            List<PaperDetailAuto> pdalist = PaperDetailAutoProxy.GetPaperDetailAuto(pi.ID.ToString());
            if (pdalist != null && pdalist.Count > 0)
            {
                var retCode = sth.ID;
                List<DBQuestion> dBQuestion = new List<DBQuestion>();
                try
                {
                    #region 选择题目
                    foreach (PaperDetailAuto pda in pdalist)
                    {
                        if (pda != null && pda.ExerciseCount > 0)
                        {
                            List<DBQuestion> exitDBQuestion = DBQuestionProxy.GetPaperExitDBQuestion(retCode.ToString());                            
                            List<DBQuestion> dBQuestionList = DBQuestionProxy.GetAll(pda);
                            int existscount = DBQuestionProxy.GetEixstsed(exitDBQuestion, pda);
                            if (dBQuestionList != null && dBQuestionList.Count >= pda.ExerciseCount)
                                GetQuestionList(ref dBQuestion, pda.ExerciseCount, dBQuestionList, exitDBQuestion, existscount);
                            else
                            {
                                sucess = false;
                                break;
                            }
                        }
                    }
                    #endregion
                }
                catch { sucess = false; }
                if (sucess && dBQuestion != null && dBQuestion.Count > 0)
                {
                    #region 添加学生题目
                    
                    if (dBQuestion != null && dBQuestion.Count > 0)
                    {
                        string rightanswer = string.Empty;
                        StudentTestQuestion tempstq = new StudentTestQuestion();
                        tempstq.Status = 1;
                        tempstq.StudentAnswer = "";
                        tempstq.StudentPoint = 0;
                        tempstq.TestHistoryID = retCode;

                        try
                        {
                            var tempRetCode = new Guid();
                            foreach (DBQuestion dbq in dBQuestion)
                            {
                                List<DBAnswer> dalist = DBAnswerProxy.GetQuestionAnswer(dbq.ID.ToString());
                                if (dalist != null && dalist.Count > 0)
                                {
                                    rightanswer = GetRightAnswer(dalist);
                                    StudentTestQuestion stq = tempstq;
                                    stq.Point = dbq.Point;
                                    stq.RightAnswer = rightanswer;
                                    stq.QuestionID = dbq.ID;
                                    stq.AnswerTime = System.DateTime.Now;
                                    if (!ProxyQuestion.CheckStudentPaper(dbq.ID.ToString(), retCode.ToString()))
                                        tempRetCode = ProxyQuestion.Insert(stq);          
                                }
                            }
                        }
                        catch { sucess = false; }
                    }

                    #endregion
                }
            }
            return sucess;
        }


        private bool StudentPaperQuestionAdd(List<PaperQuestion> list, Guid sthid)
        {
            bool sucess = true;
            if (list != null && list.Count > 0)
            {
                int count = list.Count;
                string rightanswer = string.Empty;
                List<string> deleteids = new List<string>();
                StudentTestQuestion tempstq = new StudentTestQuestion();
                tempstq.Status = 1;
                tempstq.StudentAnswer = "";
                tempstq.StudentPoint = 0;
                tempstq.TestHistoryID = sthid;
                try
                {
                    foreach (PaperQuestion psq in list)
                    {
                        List<DBAnswer> dalist = DBAnswerProxy.GetQuestionAnswer(psq.ID.ToString());
                        if (dalist != null && dalist.Count > 0)
                        {
                            rightanswer = GetRightAnswer(dalist);
                            StudentTestQuestion stq = tempstq;
                            stq.Point = psq.Point;
                            stq.RightAnswer = rightanswer;
                            stq.QuestionID = psq.ID;
                            stq.AnswerTime = System.DateTime.Now;
                            var tempRetCode = ProxyQuestion.Insert(stq);
                            if (tempRetCode != null)
                                deleteids.Add(tempRetCode.ToString());
                            else
                            {
                                sucess = false;
                                break;
                            }
                        }
                    }
                }
                catch { sucess = false; }
                if (count != deleteids.Count)
                    ProxyQuestion.Delete(deleteids);
            }
            else
                sucess = false;

            return sucess;
        }
        
        public string GetPlayer(string path)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<object id=\"player\" height=\"302px\" width=\"300px\" ");
            sb.Append(" classid=\"CLSID:22D6f312-B0F6-11D0-94AB-0080C74C7E95\">");//CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6
            sb.Append(" <param name=\"AutoStart\" value=\"1\">");
            sb.Append(" <param name=\"Balance\" value=\"0\">");
            sb.Append(" <param name=\"enabled\" value=\"0\">");
            sb.Append(" <param name=\"EnableContextMenu\" value=\"1\">");

            sb.Append("<param name=\"url\" value=\"");
            sb.Append(@"F:\Test_Resource\FileNameCheck\MV\7000992.mpg");
            sb.Append("\"> ");

            sb.Append("<param name=\"PlayCount\" value=\"1\">");
            sb.Append("<param name=\"rate\" value=\"1\">");
            sb.Append("<param name=\"currentPosition\" value=\"0\">");
            sb.Append("<param name=\"currentMarker\" value=\"0\">");
            sb.Append("<param name=\"defaultFrame\" value=\"0\">");
            sb.Append("<param name=\"invokeURLs\" value=\"0\">");
            sb.Append("<param name=\"baseURL\" value=\"\">");
            sb.Append("<param name=\"stretchToFit\" value=\"1\">");
            sb.Append("  <param name=\"volume\" value=\"50\">");
            sb.Append(" <param name=\"mute\" value=\"1\">");
            sb.Append(" <param name=\"uiMode\" value=\"None\">");
            sb.Append("<param name=\"windowlessVideo\" value=\"-1\">");
            sb.Append("<param name=\"fullScreen\" value=\"0\">");
            sb.Append("<param name=\"enableErrorDialogs\" value=\"0\">");
            sb.Append("</object> ");

            return sb.ToString();
        }

        public String BuildQuestionList(List<StudentPaperQuestionAnswer> spqalist, ref int showindex, string host)
        {
            StringBuilder questionlist = new StringBuilder();
            foreach (StudentPaperQuestionAnswer spqa in spqalist)
            {
                if (showindex == 0 && string.IsNullOrEmpty(spqa.studentPaperQuestion.StudentAnswer))
                {
                    showindex = spqa.questionindex; break;
                }
            }
            
            showindex = showindex == 0 ? 1 : showindex;
 

            foreach (StudentPaperQuestionAnswer spqa in spqalist)
            {
                questionlist.Append(StudentPaperTest(spqa.listDBAnswer, spqa.studentPaperQuestion, spqa.questionindex, host, showindex));
            }

            return questionlist.ToString();
        }

        private String StudentPaperTest(List<DBAnswer> list, StudentPaperQuestion spd, int rowindex, string host, int showindex)
        {
            StringBuilder sb = new StringBuilder("");
            StringBuilder subplname = new StringBuilder("");
            //subpl.ID = "" + rowindex.ToString();
            //subpl.Visible = visible;
            sb.AppendFormat("<div id=\"questiondiv_{0}\" {1}>", rowindex, (rowindex == showindex ? "" : "style=\"display:none\""));

            if (spd.SubjectType.Equals("视听"))
            {
                #region

                sb.Append("<div class=\"shitingdiv\">");
                sb.AppendFormat("<object id=\"player_{0}\"",rowindex);
                sb.Append(" height=\"64\" width=\"360\" classid=\"CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6\">  ");
                sb.Append("<param name=\"AutoStart\" VALUE=\"0\">  ");
                sb.Append("<param name=\"Balance\" VALUE=\"0\">  ");
                sb.Append("<param name=\"enabled\" value=\"-1\">  ");
                sb.Append("<param name=\"EnableContextMenu\" VALUE=\"-1\">  ");
                sb.Append("<param name=\"url\" value=\"");
                sb.AppendFormat("{0}/View/Student/Audio.ashx?mvurl={1}\">", host, spd.AttachFile);
                sb.Append("<param name=\"PlayCount\" VALUE=\"1\">  ");
                sb.Append("<param name=\"rate\" value=\"1\">  ");
                sb.Append("<param name=\"currentPosition\" value=\"0\">  ");
                sb.Append("<param name=\"currentMarker\" value=\"0\">  ");
                sb.Append("<param name=\"defaultFrame\" value=\"\">  ");
                sb.Append("<param name=\"invokeURLs\" value=\"0\">  ");
                sb.Append("<param name=\"baseURL\" value=\"\">  ");
                sb.Append("<param name=\"stretchToFit\" value=\"0\">  ");
                sb.Append("<param name=\"volume\" value=\"50\">  ");
                sb.Append("<param name=\"mute\" value=\"0\">  ");
                sb.Append("<param name=\"uiMode\" value=\"mini\">  ");
                sb.Append("<param name=\"windowlessVideo\" value=\"0\">  ");
                sb.Append("<param name=\"fullScreen\" value=\"0\">  ");
                sb.Append("<param name=\"enableErrorDialogs\" value=\"-1\">  ");
                sb.Append("<param name=\"SAMIStyle\" value>  ");
                sb.Append("<param name=\"SAMILang\" value>");
                sb.Append("<param name=\"SAMIFilename\" value>  ");
                sb.Append("</object></div>");

                #endregion
            }

            if ("dbsubject".Equals(spd.PQuestionType.ToString()))
            {
                #region
                sb.Append("<div class=\"main985-top subjec_a\">");
                sb.AppendFormat("<span class=\"ico\" onclick=\"showSubject('{0}','{1}');\">点击显示大题内容</span>",
                    spd.STQID, spd.STitle ?? "");
                sb.Append("</div>");
                #endregion
            }

            sb.AppendFormat("<ul class=\"subject\">{0}.  {1}</ul>", rowindex, spd.Content);

            string checkedstr = string.Empty, strid = string.Empty;
            if (spd.QuestionType.Equals("多选"))
            {
                subplname.Append("2");
                //sb.Append("<div class=\"ques-choosecont\">");
                //sb.Append("</div>");
                foreach (DBAnswer dBanswer in list)
                {
                    #region 多选

                    if (spd.StudentTestHistoryStatus != null && spd.StudentTestHistoryStatus == -1)
                    {
                        checkedstr = (!string.IsNullOrEmpty(spd.StudentAnswer) && spd.StudentAnswer.Contains(dBanswer.Prefix.Trim())) ? "checked=\"checked\"" : string.Empty;
                    }
                    strid = string.Format("{0}_radchk_{1}_{2}", dBanswer.Prefix.Trim(), rowindex, dBanswer.ID);
                    subplname.AppendFormat("/{0}", strid);

                    sb.Append("<div class=\"plq\">");
                    sb.AppendFormat("<input id=\"{1}\" value=\"{0}\"",
                        dBanswer.Prefix.Trim(), strid);
                    sb.AppendFormat("name=\"radchk_{0}\" type=\"checkbox\" class=\"chkrad\"", rowindex);
                    sb.AppendFormat(" {0} />", checkedstr);
                    sb.AppendFormat("<span class=\"prefix\">{0}</span>", dBanswer.Prefix.Trim());
                    sb.AppendFormat(" <span class=\"subjectanswer\">{0}</span>", dBanswer.Content);
                    sb.Append("</div>");
                    checkedstr = string.Empty; strid = string.Empty;
                    #endregion
                }
            }
            else
            {
                int radchecked = 0;
                subplname.Append("1");
                foreach (DBAnswer dBanswer in list)
                {
                    #region 单选

                    if (spd.StudentTestHistoryStatus != null && spd.StudentTestHistoryStatus == -1 && radchecked == 0)
                    {
                        checkedstr = (!string.IsNullOrEmpty(spd.StudentAnswer) && spd.StudentAnswer.Contains(dBanswer.Prefix.Trim())) ? "checked=\"checked\"" : string.Empty;
                        radchecked = 1;
                    }
                    strid = string.Format("{0}_radchk_{1}_{2}", dBanswer.Prefix.Trim(), rowindex, dBanswer.ID);
                    subplname.AppendFormat("/{0}", strid);

                    sb.Append("<div class=\"plq\">");
                    sb.AppendFormat("<input id=\"{1}\" value=\"{0}\"",
                        dBanswer.Prefix.Trim(), strid);
                    sb.AppendFormat("name=\"radchk_{0}\" type=\"radio\" class=\"chkrad\"", rowindex);
                    sb.AppendFormat(" {0} />", checkedstr);
                    sb.AppendFormat("<span class=\"prefix\">{0}</span>", dBanswer.Prefix.Trim());
                    sb.AppendFormat(" <span class=\"subjectanswer\">{0}</span>", dBanswer.Content);
                    sb.Append("</div>");
                    checkedstr = string.Empty; strid = string.Empty;

                    #endregion
                }
            }

            sb.AppendFormat("<input type=\"hidden\" id=\"lblq_{0}\" value=\"{1}\" name=\"{2}\" />",
                rowindex, spd.StudentTestQuestionID.ToString(), subplname);
            sb.Append("</div>");

            return sb.ToString();
        }
    }
}
